<!--用户管理-->
<template>
  <div class="userManagement">
    <!-- 搜索表单 -->
    <el-form
      :inline="true"
      :model="searchForm"
      ref="searchForm"
      label-width="70px"
    >
      <div class="main">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyword"
            placeholder="用户/手机号/姓名搜索"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="onSubmit" type="primary">查询</el-button>
          <!-- <el-button @click="onClear">重置</el-button> -->
        </el-form-item>
      </div>
    </el-form>
    <!-- 数据列表 -->
    <el-editable
      class="el-table"
      :data="tableData"
      height="200"
      :custom-attr="$TABLE_HEAD['systemSetup.userManagement.list']"
      v-loading="tableLoading"
      :columns="userManagement"
      @selection-change="handleSelectionChange"
    >
      <template slot="default-idCard" slot-scope="scope">
        <span>
          {{ scope.row.idCard }}
        </span>
      </template>
      <template slot="default-btnGroup" slot-scope="scope">
        <el-button
          size="medium"
          @click.stop="unlockHandler(scope.row.id)"
          type="text"
          >解锁</el-button
        >
      </template>
    </el-editable>
    <!-- 分页 -->
    <el-pagination
      class="pagination"
      align="right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="curPage"
      :page-sizes="PAGE_NUMBER"
      :page-size="pageSize"
      :layout="PAGINATION_LAYOUT"
      :total="total"
    />
    <!-- 新增弹框 -->
    <el-dialog
      :title="!isEditUser ? '新增用户' : '修改用户'"
      :visible.sync="dialogVisibleEdit"
      class="dialog-box"
      width="55%"
      @close="resetForm"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        inline
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input
            v-model="editForm.loginName"
            placeholder="请输入"
            clearable
            maxlength="16"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            placeholder="请输入"
            type="password"
            show-password
            :disabled="isEditUser"
            autocomplete="new-password"
            maxlength="16"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input
            v-model="editForm.userName"
            placeholder="请输入"
            clearable
            maxlength="16"
          />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input
            v-model="editForm.phone"
            placeholder="请输入"
            clearable
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editForm.gender" placeholder="请选择">
            <el-option
              v-for="item in gender"
              :key="item.val"
              :label="item.lab"
              :value="item.val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="mail">
          <el-input
            v-model="editForm.mail"
            placeholder="请输入"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input
            v-model="editForm.idCard"
            placeholder="请输入"
            maxlength="30"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click.stop="dialogVisibleEdit = false">取消</el-button>
        <el-button
          type="primary"
          @click.stop="submitEditForm"
          :loading="addUserLoading"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog title="导入成功" :visible.sync="importVisible" width="30%">
      <ul>
        <li
          style="liststyle:none;"
          v-for="(item, index) in importData"
          :key="index"
        >
          {{ item }}
        </li>
      </ul>
    </el-dialog>
  </div>
</template>
<script>
import ElEditable from '@components/el-editable/door/index.vue'
import {PAGE_NUMBER, PAGINATION_LAYOUT} from '@const/common.js'
import {
  username,
  realName,
  password,
  phone,
  email,
  checkIdCard
} from '@const/formValidate.js'
import {userManagement, approveStatus, gender} from './const.js'
import {
  merchantUserPageListLocked,
  UcMerchantUserUpdate,
  UcMerchantUserSave,
  updateStatusById,
  UcMerchantUserDeleteById,
  UcMerchantUserGetUserPower,
  updateUserAuditStatus,
  UcMerchantUserAddUserPower,
  UcMerchantPostInstUpdate,
  deletePositionInstByUserId,
  getAllNoAuthenticationUser,
  authenticationUser,
  addUser,
  updateUser,
  deleteUserById,
  deleteBatchUserByIds,
  userExport,
  merchantUserImportUser,
  updateAuditStatus,
  merchantUserUnlockUser
} from '@const/api_staffCenter.js'
import {fileUpload} from '@const/api_aggregation.js'
import {hasIn, cloneDeep} from 'lodash'
import {$loadFileSimply} from '@const/loadFileOps' // 下载文件的方法
import {fileDownload} from '@const/utils' // 内容转化为文件下载
import md5 from 'js-md5'
export default {
  name: 'UserManagement',
  components: {ElEditable},
  data() {
    return {
      approveStatus,
      gender,
      curPage: 1,
      PAGE_NUMBER, // 页码
      PAGINATION_LAYOUT, // 分页功能
      pageSize: PAGE_NUMBER[0], // 一页的数量
      userManagement, // 表头信息
      total: 0, // 总页数
      tableData: [], // 表格数据
      searchForm: {
        keword: '',
        status: ''
      },
      // 编辑用户
      editForm: {
        id: '',
        loginName: '',
        userName: '',
        password: '',
        phone: '',
        gender: '',
        mail: '',
        idCard: ''
      },
      addUserLoading: false, // 新增用户确定按钮loading
      dialogVisibleEdit: false, // 新增用户弹框
      // 编辑新建弹出层的校验
      editFormRules: {
        loginName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        userName: realName(),
        phone: phone(),
        mail: email(),
        gender: [{required: true, message: '请选择性别', trigger: 'blur'}]
      },
      isEditUser: false, // 新增true 编辑false
      tableLoading: false, // table的loading
      userDialog: {
        visible: false,
        loading: false,
        btnLoading: false,
        checkList: [],
        searchKey: '',
        userList: []
      },
      selectionList: [],
      fileList: [],
      uploadAccept: '.xls,.xlsx',
      importData: [],
      importVisible: false,
      downloadUrl:
        'https://md.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/91sefo5xpdtg8abi72i7vg2rnyu544ix.xls'
    }
  },
  created() {
    this.query()
  },
  methods: {
    unlockHandler(id) {
      this.$axios({
        method: 'POST',
        url: merchantUserUnlockUser,
        data: {id: id}
      })
        .then(res => {
          if (res.data.code === '0') {
            this.$message.success('解锁成功')
          }
          this.query()
        })
        .finally(() => {})
    },
    query() {
      this.tableLoading = true
      this.$axios({
        method: 'GET',
        url: `${merchantUserPageListLocked}?page=${this.curPage}&pageSize=${
          this.pageSize
        }&keyword=${this.searchForm.keyword || ''}`
      })
        .then(res => {
          let arr = hasIn(res, ['data', 'payload']) ? res.data.payload : {}
          this.tableData = arr.content ? arr.content : []
          this.total = arr.totalElements ? arr.totalElements : 0
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    //得到选中的数据
    handleSelectionChange(val) {
      this.selectionList = val
    },
    //导入
    beforeUpload(file) {
      let FileExt = file.name.replace(/.+\./, '') // 名字后缀
      const format = this.uploadAccept.includes(FileExt.toLowerCase())
      if (!format) {
        this.$message.error(`上传文件只支持${this.uploadAccept}类型!`)
        return false
      }
    },
    async toRequest(dataA) {
      let fd = new FormData()
      fd.append('file', dataA.file)
      await this.$axios({
        method: 'post',
        url: merchantUserImportUser,
        headers: {'Content-Type': 'multipart/form-data'},
        data: fd
      })
        .then(res => {
          const {data} = res
          if (!Number(data.code)) {
            if (data.payload !== null) {
              this.importData = data.payload
              this.importVisible = true
            } else {
              this.$message.success('导入成功')
            }
            this.query()
          } else {
            this.$message.error(data.msg)
          }
        })
        .finally(() => {})
    },
    handleAvatarSuccess() {},
    handleImport() {},
    //导出
    handleExport() {
      this.$confirm('确定要导出数据吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.importExcel()
        })
        .catch(res => {
          console.log(res)
        })
    },
    // 导出所有产品
    importExcel() {
      let param = {
        method: 'get',
        url: userExport // 导出接口待定
      }
      $loadFileSimply(param).then(res => {
        // 文件流
        fileDownload(res, `用户列表.xls`)
      })
    },
    // 清空用户列表
    clearListHandle() {
      this.userDialog.checkList = []
    },
    // 添加用户
    addUserList() {
      this.userDialog.btnLoading = true
      this.$axios({
        url: authenticationUser,
        method: 'post',
        data: {
          userIdList: this.userDialog.checkList
        }
      }).then(res => {
        this.query()
        this.userDialog.visible = false
        this.userDialog.btnLoading = false
      })
    },
    resetForm() {
      this.editForm = {
        id: '',
        loginName: '',
        userName: '',
        password: '',
        phone: '',
        gender: '',
        mail: '',
        idCard: ''
      }
    },
    submitEditForm() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          if (this.editForm.idCard) {
            let reg = checkIdCard(this.editForm.idCard)
            if (!reg) {
              this.$message({
                message: '请输入正确的身份证信息',
                type: 'warning'
              })
              return false
            }
          }
          this.isEditUser ? this.updateUser() : this.addUser()
        } else {
          return false
        }
      })
    },
    // 清空查询条件
    onClear() {
      this.searchForm = {keyword: '', status: '', gender: ''}
      this.query()
    },
    downloadTemplate() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = this.downloadUrl
      link.setAttribute('download', '用户导入模板.xls')
      document.body.appendChild(link)
      link.click()
    },
    // 打开新增用户面板
    determine() {
      this.dialogVisibleEdit = true
      this.isEditUser = false
    },
    // 审核
    auditHandler(row, status) {
      this.$confirm(
        `是否确认${status === 1 ? '通过审核' : '驳回'}该用户？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.$axios({
          method: 'post',
          url: updateAuditStatus,
          data: {auditStatus: status, id: row.id}
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$message.success('操作成功')
              this.query()
            }
          })
          .finally(() => {})
      })
    },
    // 表格修改按钮
    editUserHandler(scope) {
      this.editForm.idCard = scope.row.idCard
      for (let item in this.editForm) {
        this.editForm[item] = scope.row[item] || ''
      }
      this.isEditUser = true
      this.dialogVisibleEdit = true
    },
    // 确认修改按钮
    updateUser() {
      this.tableLoading = true
      this.addUserLoading = true
      delete this.editForm.password
      this.$axios({
        method: 'post',
        url: updateUser,
        data: this.editForm
      })
        .then(() => {
          this.resetForm()
          this.query()
          this.dialogVisibleEdit = false
        })
        .finally(() => {
          this.tableLoading = false
          this.addUserLoading = false
        })
    },
    // 新增用户确定按钮
    addUser() {
      this.addUserLoading = true
      this.$axios({
        method: 'post',
        url: addUser,
        data: {
          ...this.editForm,
          // 传入password为空的情况，不进行md加密
          password:
            this.editForm.password.replace(' ', '') === ''
              ? ''
              : md5(this.editForm.password)
        }
      })
        .then(data => {
          this.$message({message: '用户新增成功', type: 'success'})
          this.query()
          this.dialogVisibleEdit = false
        })
        .finally(() => {
          this.addUserLoading = false
        })
    },
    // 启用、停用,冻结，解冻用户
    Toexamine(scope, type) {
      let status = 1
      if (type == 1) {
        status = 2
      } else {
        status = 3
      }
      this.$confirm(
        `是否确认${
          scope.row.status === 1
            ? type == 1
              ? '停用'
              : '冻结'
            : type == 1
            ? '启用'
            : '解冻'
        }该用户？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.tableLoading = true
        this.$axios({
          method: 'post',
          url: updateStatusById,
          data: {
            id: scope.row.id,
            status: scope.row.status === 1 ? status : 1
          }
        }).then(res => {
          this.query()
        })
      })
    },
    // 表格内的删除
    handleTableRowDel(scope) {
      this.$confirmCustom().then(() => {
        this.delete(scope)
      })
    },
    //获取选中数据的每项id
    getSelectionListIds() {
      return this.selectionList.reduce((pre, cur) => {
        return [...pre, cur.id]
      }, [])
    },
    handleSelectionDel() {
      if (this.selectionList && this.selectionList.length > 0) {
        this.$confirm('此操作将永久当前用户, 是否继续?', '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableLoading = true
          this.$axios({
            method: 'post',
            url: deleteBatchUserByIds,
            data: {
              idList: this.getSelectionListIds()
            }
          })
            .then(() => {
              this.$message({
                message: '删除成功！',
                type: 'success'
              })
              this.query()
            })
            .finally(() => {
              this.tableLoading = false
            })
        })
      } else {
        this.$message({
          message: '请选择要删除的数据',
          type: 'warning'
        })
      }
    },
    // 删除
    delete(scope) {
      this.$confirm('此操作将永久当前用户, 是否继续?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true
        this.$axios({
          method: 'post',
          url: deleteUserById,
          data: {
            id: scope.row.id
          }
        })
          .then(() => {
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
            this.query()
          })
          .finally(() => {
            this.tableLoading = false
          })
      })
    },
    // 根据条件查询
    onSubmit() {
      this.curPage = 1
      this.query()
    },
    // 更改页码大小
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.query()
    },
    // 更改当前页
    handleCurrentChange(curPage) {
      this.curPage = curPage
      this.query()
    }
  }
}
</script>
<style lang="less" type="text/less">
.userManagement {
  display: flex;
  flex-direction: column;
  .menu-list {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
  }
  .el-form {
    .el-input {
      width: 211px;
    }
  }

  .dialog-box {
    .el-input {
      width: 211px;
    }
  }

  .el-table {
    margin-top: 15px;
    flex: 1;
  }

  .pagination {
    margin-top: 10px;
  }

  .dialog-new-btn {
    float: right;
    margin-bottom: 10px;
  }
  .add-company-dialog {
    height: 500px;
    display: flex;
    flex-direction: column;

    .dialog-checked-all {
      margin: 16px 0;
    }

    .checkbox-box {
      flex: 1;
      margin-top: 10px;
      margin-right: 10px;
      overflow: auto;

      .el-checkbox {
        display: block;
        margin-left: 0;
      }
    }
  }
}
.el-message--warning {
  z-index: 9999 !important;
}
</style>
